package portal.monitor.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.UUID;

import portal.monitor.utils.MonBaseUtils;
import portal.monitor.utils.MonConfig;
import utils.Log4jInit;
import utils.StreamGobbler;

public class CommCmd {

		public static String makeExcScript(String cmd){
			
			String scriptFileUri = MonConfig.localBase+"script/";
			File scriptFile = new File(scriptFileUri);
			if (!scriptFile.exists()) {
				scriptFile.mkdirs();
			}
				try {
					MonBaseUtils.chmod(scriptFileUri);
					String scriptUri = scriptFileUri + UUID.randomUUID().toString().substring(0, 15) + ".sh";
					File algorithmBatFile = new File(scriptUri);
					FileWriter fw = new FileWriter(algorithmBatFile);
					MonBaseUtils.chmod(scriptUri);
					fw.write(cmd);
					fw.close();
					return scriptUri;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		return "ERROR";
		}
		
		
		public static String getCmdRetStr(String scriptPath){
			
			try {
				// 执行命令
				Process p = Runtime.getRuntime().exec(scriptPath);

				/* 为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞 */
				Thread t = new Thread(new StreamGobbler(p.getErrorStream(), "ErrorStream"));
				t.start();

				// 取得命令结果的输出流
				InputStream fis = p.getInputStream();
				// 用一个读输出流类去读
				InputStreamReader isr;
				isr = new InputStreamReader(fis, "UTF-8");
				// 用缓冲器读行
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				StringBuffer sb = new StringBuffer();
				// 直到读完为止
			
					while ((line = br.readLine()) != null) {
						sb.append(line);
					//	sb.append("</br>\n");
						sb.append("#");
					}
//					String strUtf8 = new String(sb.toString().getBytes("gbk"));  
					String strUtf8 = new String(sb.toString().getBytes("UTF-8")); 
					Log4jInit.logger.info("====READ CMD OUTPUT===\n"+strUtf8);
					
				return strUtf8;
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		return "ERROR";
			
		}
	
}
